<?php

namespace app\api\middleware;


use app\common\enum\Code;
use app\common\Result;
use ReflectionException;
use think\Request;

class Init
{

    public function handle(Request $request, \Closure $next)
    {
        [$module, $controller, $action] = get_mca();
        if (empty($module) || empty($controller) || empty($action)) {
            Result::httpExceptionByCode(Code::AppError);
        }

        $className = 'app\\' . $module . '\controller\\' . $controller;
        if (!class_exists($className)) {
            Result::httpExceptionByCode(Code::ControllerNotFound);
        }

        try {
            $reflect = new \ReflectionClass($className);
            $hasMethod = $reflect->hasMethod($action);
            if (!$hasMethod) {
                Result::httpExceptionByCode(Code::ActionNotFound);
            }

        } catch (ReflectionException $e) {
            Result::httpException($e->getMessage());
        }

        return $next($request);
    }
}